;
(function (window, angular) {
    'use strict';
    angular.module("Controller.BasicData.PriceScheme", [])
        .controller("PriceSchemeCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "$filter", "UserContextService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, $filter, UserContextService) {
            $scope.activeFlag = [true, false, false];
            $scope.markInfo = {
                cueRow: ""
            };
            $scope.toolbarConfig = {
                showColConfig: false
            };
            $scope.isAllDisabled = false
            $scope.submitted = false;
            $scope.dataList = [];
            $scope.detailInfo = {
                modeType: 0,
                state: 1,
                isAllMaterials: 0
            };
            $scope.priceTypeList = [
                {
                    id: 0,
                    name: "销售价"
                },
                {
                    id: 1,
                    name: "标准价"
                },
                {
                    id: 2,
                    name: "采购最高价"
                }
            ];
            $scope.priceSchemeType = [
                {
                    id: 0,
                    name: "固定折扣"
                },
                {
                    id: 1,
                    name: "指定价格"
                }
            ];
            //add by spd 方案类型
            $scope.schemeTypeList = [{
                id: 0,
                name: "常规"
            },
            {
                id: 1,
                name: "价格折让"
            },
            {
                id: 2,
                name: "促销活动"
            }
            ];
            //add by lqx

            $scope.tabFlag = {};
            $scope.config = {
                client: false
            };
            var tabFlag = {
                0: "新增",
                1: "编辑"
            };
            $scope.priceTbConf = {
                fixedWidth: 370,
                scrollWidth: 1100,
                tableCol: [
                    {
                        type: "",
                        name: "价格方案名称",
                        dataField: "name",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "价格组",
                        dataField: "priceGroup",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "折扣类型",
                        dataField: "modeTypeShow",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    //add by spd
                    {
                        type: "",
                        name: "方案类型",
                        dataField: "schemeTypeShow",
                        width: 80,
                        isShow: $scope.isWJ,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "应用所有零件",
                        dataField: "isAllMaterialsShow",
                        width: 90,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "状态",
                        dataField: "stateShow",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "创建人",
                        dataField: "createName",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "创建时间",
                        dataField: "createDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "更新人",
                        dataField: "updateName",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "更新时间",
                        dataField: "updateDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "币种",
                        dataField: "currency",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },     
                    {
                        type: "",
                        name: "零件分类",
                        dataField: "materialsType",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },                 
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 370,
                        isShow: true,
                        isFixed: true,
                    }
                ]
            };
            $scope.shuttleConf = {
                leftTbConf: {
                    scrollWidth: 1000,
                    tableCol: [
                        {
                            name: "客户名称",
                            dataField: "companyName",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "客户代码",
                            dataField: "dealerOrgId",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "联系人",
                            dataField: "contact",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "联系电话",
                            dataField: "contactTel",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                        }
                    ]
                },
                checkFiled: "dealerOrgId",
                leftDataConf: {
                    service: "device",
                    reqUrl: "/companyDealer/listForPriceScheme",
                    reqType: "Post",
                    page: true,
                    condition: {
                        name: "客户名称",
                        key: "companyNames"
                    }
                }
            };
            $scope.selectPriceSchemeId = "";

            $scope.handleSaveOrRemoveDealer = function(param) {
                var service = "device";
                var reqUrl = "/marketingActivity/saveOrRemoveDealer";
                param.activityId = $scope.selectPriceSchemeId;
                return ybHttp.Post(service, reqUrl, param);
            };

            $scope.setClient = function (schemeId) {
                $scope.selectPriceSchemeId = schemeId;
                $scope.shuttleConf.leftDataConf.otherParams = { activeId: schemeId };
                $scope.changeTab(2);
            };

            var btnPermissionCode = {
                priceSchemeAdd: window.ActionCode.priceSchemeAdd,
                priceSchemeEdit: window.ActionCode.priceSchemeEdit,
                priceSchemeDel: window.ActionCode.priceSchemeDel,
                priceSchemeSetClient: window.ActionCode.priceSchemeSetClient,
                priceSchemeSync: window.ActionCode.priceSchemeSync,
                priceSchemeSyncIncrement: window.ActionCode.priceSchemeSyncIncrement
            };

            $scope.btnPermission = {
                priceSchemeAdd: true,
                priceSchemeEdit: true,
                priceSchemeDel: true,
                priceScheme: true,
                priceSchemeSync: true,
                priceSchemeSyncIncrement: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: { left: $scope.priceTbConf.fixedWidth + "px" },
                    scrollLeftWidth: { width: $scope.priceTbConf.fixedWidth + "px" }
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {
                    modeType: 0,
                    state: 1,
                    isAllMaterials: 0
                };

                $scope.selectedData = { countryObj: {} };
                
                $scope.config.client = false;
            }

            $scope.condition = {};

            function getDataList() {
                var service = "device";
                var reqUrl = "/marketingActivity/list";
                ybHttp.Get(service, reqUrl, $scope.condition).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value, function (item) {
                        item.isChecked = false;
                        item.modeTypeShow = $filter("TrueOrFalse")(item.modeType, "priceScheme");
                        item.isAllMaterialsShow = $filter("TrueOrFalse")(item.isAllMaterials, "normal");
                        item.stateShow = $filter("TrueOrFalse")(item.state, "enabled");
                        item.createDateShow = $filter("YbDate")(item.createDate);
                        item.updateDateShow = $filter("YbDate")(item.updateDate);
                        //add by spd 
                        item.schemeTypeShow = $filter("TrueOrFalse")(item.schemeType, "schemeType");
                    });

                    $scope.dataList = resp.value;
                });
            }

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.addData = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                $scope.isAllDisabled = false
                $scope.changeTab(1);
            };

            $scope.delData = function (id) {
                var service = "device";
                var reqUrl = "/marketingActivity/remove";
                var param = {
                    id: id
                };
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                }, function () {

                })
            };

            $scope.editData = function (item) {
                $scope.detailInfo = angular.copy(item);
                $scope.changeMat()
                if (!!$scope.detailInfo.validDateStart) {
                    $scope.detailInfo.validDateStart = $filter("YbDate")(item.validDateStart, 'yyyy-MM-dd');
                }
                if (!!$scope.detailInfo.validDateEnd) {
                    $scope.detailInfo.validDateEnd = $filter("YbDate")(item.validDateEnd, 'yyyy-MM-dd');
                }
                if ($scope.detailInfo.priceType) {
                    $scope.detailInfo.priceType = Number($scope.detailInfo.priceType);
                }

                $scope.selectedData = {
                    countryObj: {
                        ids: item.countryList
                    }
                };
                //add by lqx
                if ($scope.detailInfo.schemeType) {
                    $scope.detailInfo.schemeType = Number($scope.detailInfo.schemeType);
                }
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                $scope.changeTab(1);
            };

            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/marketingActivity/add";
                var param = angular.copy($scope.detailInfo);
                param.countryList = $scope.selectedData.countryObj.ids; // 所属区域(国家code)

                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/marketingActivity/update";
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if (!!$scope.config.client) {
                        $scope.setClient(resp.value, "new");
                    } else {
                        $scope.changeTab(0);
                    }
                    getDataList();
                    $scope.markInfo.allChecked = false;
                });
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.syncSap = function (type) {
                ybWidget.ShowMessage("确认从SAP同步数据吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/marketingActivity/synSap";
                    if (type === 1) {
                        reqUrl = "/marketingActivity/synSapIncrement";
                    }
                    ybHttp.Get(service, reqUrl);
                    ybWidget.ShowMessage("正在后台同步，会占用较长时间，请稍候再进行查看。", MESG_TYPE.Note);
                }, function () {

                });
            };

            $scope.importMateriel = function (item) {
                var param = {
                    name: "价格方案",
                    templateReqService: "device",
                    templateReqUrl: "/marketingActivity/download",
                    importReqService: "device",
                    importReqUrl: "/marketingActivity/import",
                    importErrorUrl: "",
                    billId: item.id,
                    orgId: item.orgId
                };
                ybWidget.ImportFile(param).then(function (data) {

                });
            };
            $scope.changeMat = function () {
                if ($scope.detailInfo.sapPurchaseType || $scope.detailInfo.sapMrpCon || $scope.detailInfo.sapAttrDes) {
                    $scope.isAllDisabled = true
                    $scope.detailInfo.isAllMaterials = 0
                }
                if (!$scope.detailInfo.sapPurchaseType && !$scope.detailInfo.sapMrpCon && !$scope.detailInfo.sapAttrDes) {
                    $scope.isAllDisabled = false
                }
            };
            $scope.configuration = function (item) {
                var activityIdList = [];
                activityIdList.push(item.id);
                var service = "device";
                var reqUrl = "/marketingActivity/batchSaveDealer";
                var param = {
                    activityIdList: activityIdList
                };
                ybWidget.ShowMessage("确定要一键配置所有客户吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                }, function () {})
            };

            // 清除所有客户
            $scope.clearAllUser = function (item) {
                var activityIdList = [];
                activityIdList.push(item.id);
                var reqUrl = "/marketingActivity/batchRemoveDealer";
                var param = {
                    activityIdList: activityIdList
                };
                ybWidget.ShowMessage("确定要一键清空所有客户吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post('device', reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.selectedData = { countryObj: {} };
            $scope.changeMode = function(){
                // 清空零件分类
                if ($scope.detailInfo.modeType == 1) {
                    $scope.detailInfo.materialsType = ''
                    $scope.detailInfo.materialsTypeId = ''
                }
            }
            $scope.$watch('detailInfo.materialsType', function() {
                if ($scope.detailInfo.materialsType) {
                    $scope.detailInfo.isAllMaterials  = 0
                }
            });

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();

        }]);
})(window, window.angular);